/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package store

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"github.com/pkg/errors"
)

type CertFileUserStore struct {
	store core.KVStore
}

func storeKeyFromUserIdentifier(key iam.IdentityIdentifier) string {
	return key.ID + "@" + key.IAMID + "-cert.pem"
}

func NewCertFileUserStore(store core.KVStore) (*CertFileUserStore, error) {
	return &CertFileUserStore{
		store: store,
	}, nil
}

func (s *CertFileUserStore) Load(key iam.IdentityIdentifier) (*iam.UserData, error) {
	cert, err := s.store.Load(storeKeyFromUserIdentifier(key))
	if err != nil {
		if err == core.ErrKeyValueNotFound {
			return nil, iam.ErrUserNotFound
		}
		return nil, err
	}
	certBytes, ok := cert.([]byte)
	if !ok {
		return nil, errors.New("user is not of proper type")
	}
	userData := &iam.UserData{
		IAMID:                 key.IAMID,
		ID:                    key.ID,
		EnrollmentCertificate: certBytes,
	}
	return userData, nil
}

func (s *CertFileUserStore) Store(user *iam.UserData) error {
	key := storeKeyFromUserIdentifier(iam.IdentityIdentifier{IAMID: user.IAMID, ID: user.ID})
	return s.store.Store(key, user.EnrollmentCertificate)
}

func (s *CertFileUserStore) Delete(key iam.IdentityIdentifier) error {
	return s.store.Delete(storeKeyFromUserIdentifier(key))
}
